/**
 * 公共函数
 */
import base64js from 'base64-js';
import CryptoJS from 'crypto-js';
import { passKey } from 'SERVICE/xhr/config';

let userToken = '';
export function setUserToken(token) {
  userToken = token;
}
export function clearToken() {
  userToken = '';
}
export function getUserToken(token) {
  let t = localStorage.getItem('userAuthToken');
  return userToken ? userToken : t ? t : '';
  // return userToken;
}
export function setUserTokenToLocalStorage(userAuthToken, loginName, password) {
  localStorage.setItem('userAuthToken', getUserToken(userAuthToken));
  // if (loginName && password) {
  localStorage.setItem('loginName', loginName);
  localStorage.setItem('password', password);
  // }
}
/**
 * BASE64解码
 * @param {*} base64Str
 */
export function md5Enc(string) {
  return CryptoJS.MD5(string).toString();
}

/**
 * BASE64解码
 * @param {*} base64Str
 */
export function base64Decode(base64Str) {
  let byteArr = base64js.toByteArray(base64Str);
  return new Buffer(byteArr).toString();
}


/**
 * BASE64转码
 * @param {*} base64Str
 */
export function base64Encode(str) {
  return base64js.fromByteArray(new Buffer(str));
}





export function randomAbcNumber(length){
  var text = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
  var randomData = "";
  for(var i =0;i<length;i++){
    var num = parseInt(Math.random()*36);
    randomData+=text.substring(num,num+1);
  }
  return randomData;
}
export function randomNumber(length){
  var text = "0123456789";
  var randomData = "";
  for(var i =0;i<length;i++){
    var num = parseInt(Math.random()*10);
    randomData+=text.substring(num,num+1);
  }
  return randomData;
}


export function AESEncode(str) {
  let AESKEY,AESIV;
  //rsa 加密 AESKEY
  AESKEY = CryptoJS.enc.Utf8.parse(randomAbcNumber(16));
  AESIV = CryptoJS.enc.Utf8.parse(randomNumber(16));
  var encrypt = new JSEncrypt();
   encrypt.setPublicKey(passKey)
  //对AESKEY惊醒加密
  var encryptData = encrypt.encrypt(CryptoJS.enc.Base64.stringify(AESKEY));
  //let AESKEYSave = CryptoJS.enc.Base64.stringify(AESKEY);
  let AESIVSave = CryptoJS.enc.Base64.stringify(AESIV);
  //将uri处理
  encryptData = encodeURIComponent(encryptData)
  AESIVSave = encodeURIComponent(AESIVSave);
 
  let encStr = CryptoJS.AES.encrypt(str,AESKEY, {
    iv:AESIV,
  });
  return {
    body:encStr.toString(),
    aeskey:encryptData,
    aesiv:AESIVSave,
    useKey:AESKEY,
    useIv:AESIV
  }
}

export function AESDecode(str,key,iv) {
  let decStr = CryptoJS.AES.decrypt(str,key, {
    iv: iv,
  });
  //console.log(CryptoJS.enc.Base64.stringify(decStr.ciphertext))
  return CryptoJS.enc.Utf8.stringify(decStr);
}

export function detectmob() {
  if( navigator.userAgent.match(/Android/i)
      || navigator.userAgent.match(/webOS/i)
      || navigator.userAgent.match(/iPhone/i)
      || navigator.userAgent.match(/iPad/i)
      || navigator.userAgent.match(/iPod/i)
      || navigator.userAgent.match(/BlackBerry/i)
      || navigator.userAgent.match(/Windows Phone/i)){
    //移动设备
    return "mobile";
  }else {
    //pc设备
    return "pc";
  }
}





// DES加密，在对结果进行BASE64转码
export function DESEncrypt(str, key) {
  var keyHex = CryptoJS.enc.Utf8.parse(key);
  let encStr = CryptoJS.DES.encrypt(CryptoJS.enc.Utf8.parse(str), keyHex, {
    mode: CryptoJS.mode.ECB
  });
  return encStr.toString();
}

export function isLogin() {
  return userToken != '';
}

export function getDateDiff(dateTime) {
  var dateTimeStamp = Date.parse(new Date(dateTime));
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  // var halfMonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  var result;
  if (monthC >= 1) {
    result = '' + parseInt(monthC, 10) + '月前';
  } else if (weekC >= 1) {
    result = '' + parseInt(weekC, 10) + '周前';
  } else if (dayC >= 1) {
    result = '' + parseInt(dayC, 10) + '天前';
  }else if (hourC >= 1) {
    result = '' + parseInt(hourC, 10) + '小时前';
  }else if (minC >= 1) {
    result = '' + parseInt(minC, 10) + '分钟前';
  } else {
    result = '刚刚'
  }
  return result;

}

//dateTime长度为8的字符串日期格式,如:'20180101'
//例:var dateTime='20180101';str='-'
//changeDateType(dateTime,str);
//返回'2018-01-01'
export function changeDateType(dateTime,str){
    var year = dateTime.substr(0,4);
    var month = dateTime.substr(4,2);
    var day = dateTime.substr(6,2);
    var date;
    return date = year+str+month+str+day;
}


export function getUrlParams(url){
  var name, value;
  var paramData = {};
  var str = url||location.href;
  var num = str.indexOf("?")
  if(num>0){

    str = str.split("?");
    str = str.slice(1,str.length);
    var arr = str.join("&");
    
    arr = arr.split("&");
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            paramData[name] = decodeURI(arr[i].substr(num + 1));
        }
    }
    return paramData;
  }else{
    return false;
  }

}
//获取设备信息
export function getUserAgent() {
  return navigator.userAgent;
}
//判断是否iosX
export function isIphoneX(){
  return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
}
// 判断是否是ios
export function phoneSystem() {
  var ua = navigator.userAgent;
  var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  if(android){
    return 'android';
  }
  if((ipad || iphone || ipod)){
    return 'ios';
  }
}

// 按照大小比例压缩图片 压缩的一定会用来缓存 所以压缩缓存写在一起
// 只有从服务器请求的图片才需要压缩 本地图片缓存使用 appcache
//imgPath 缓存图片路径存执key值
export function canvasDataURL(path, obj,imgPathSave) {
  //判断图片是否已经缓存 如果已经缓存直接返回结果
  var imgData = localStorage.getItem(path);

  if(!imgData){
    var img = new Image();
    img.src = path;

    img.onload = function(){

      var that = this;
      // 默认按0.8倍比例压缩
      var w = that.width,
          h = that.height,
          size = w/h;
      obj = obj || {};
      w = obj.width || w*0.8;
      h = obj.width/size || h*0.8;
      var quality = 0.9;  // 默认图片质量为0.9
      //生成canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if(obj.quality && obj.quality <= 1 && obj.quality > 0){
        quality = obj.quality;
      }
      // quality值越小，所绘制出的图像越模糊
      var base64 = canvas.toDataURL('image/jpeg', quality);
      
      // 回调函数返回base64的值
      var imgDataA = ctx.getImageData(0, 0, w, h);
      var pxData = imgDataA.data;
      w = parseInt(w);
      h = parseInt(h);
      //取出图片下面四点 如果不是黑的
      //最后一点 (w*h-1)*4  右小角一点  (w*(h-1)+4)*4
      var list = [(w*h-1)*4,(w*(h-1)+4)*4]
      var black = false;

      for(var i in list){
        var r = pxData[list[i]];
        var g = pxData[list[i]+1];
        var b = pxData[list[i]+2];
        if(r>10 || g>10 || b>10){
          black = true;
        }
      }
      if(black || imgPathSave=="thirdMenu" ){
        // 回调函数返回base64的值
        var imgPath = localStorage.getItem(imgPathSave);
        if(imgPath){
        	imgPath = imgPath+","+path
        }else{
        	imgPath = path;
        }
        
        localStorage.setItem(imgPathSave,imgPath);
        
        localStorage.setItem(path,base64);
      }
    }
    return path;
  }else{
    return imgData;
  }
}


//获取设备信息
export function clearImg(imgPathSave) {
  var imgPath = localStorage.getItem(imgPathSave);
  
  if(imgPath){
  	imgPath = imgPath.split(",");
  	for(var i in imgPath){
  		localStorage.removeItem(imgPath[i]);
  	}
  	localStorage.removeItem(imgPathSave)
  }
}

//获取设备信息
export function getLocalData(url) {
  return JSON.parse(localStorage.getItem(url));
}


//秒转化成时分秒,自动加零
export function secondToDate(result) {
    var h = Math.floor(result / 3600) < 10 ? '0'+Math.floor(result / 3600) : Math.floor(result / 3600);
    var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
    return result = h + ":" + m + ":" + s;
}

//更新缓存信息,如有信息跟新则替换
export function changeLocalStorage(list){
  var oldList=[];
  if(oldList.length==0){
    for(var i=0; i<list.length;i++){
      oldList.puch(list[i].cover)
    }
    localStorage.setItem(bannerOldList,oldList)
  }else{
    for(var i=0; i<list.length;i++){
      oldList=localStorage.getItem(bannerOldList)
      var bannerListMap;
      for(var j=0; j<oldList.length;j++){
        if(list[i].cover==oldList[j]){
          bannerListMap.puch(oldList[j])
        }else{
          bannerListMap.puch(list[i].cover)
        }
      }
    }
    localStorage.setItem(bannerOldList,bannerListMap)
  }
}

